// 监听按钮点击事件
export function trackClick() {
    const needTracks = this.needTrack('clickEvent')
    if (!needTracks.length) { return }
    const global = this
    // 监听所有的注册监听事件行为,拦截注册监听事件行为
    const oldAddEventListener = HTMLElement.prototype.addEventListener
    HTMLElement.prototype.addEventListener = function () {
        if (arguments[0] === 'click' && this.localName !== 'html') {
            const oldFunc = arguments[1]
            arguments[1] = function () {
                const clickBox = this
                const conformTracks = getConformTrack(clickBox)
                if (conformTracks.length) {
                    const conformTracksItem = conformTracks[0]
                    const insideObj = global.isInExecutes(conformTracksItem, clickBox)
                    insideObj.lastTime ? clearTimeout(insideObj.lastTime) : ''
                    insideObj.lastTime = setTimeout(() => {
                        const obj = { describe: `${clickBox.innerText}`, currentTime: new Date().getTime()}
                        global.deleteExecutesItem(conformTracksItem, clickBox)  // 清除记录对象
                        // 上报数据
                        // console.log(conformTracks, 'conformTracks')
                        global.sendDataBefore(conformTracks, 'clickEvent', obj)
                    }, 200)
                }
                oldFunc.apply(this, arguments)
            }
        }
        oldAddEventListener.apply(this, arguments)
    }
    // 查看有没符合条件的对象
    function getConformTrack(clickBox) {
        // 先查地址,不传或者传空数组就是表示所有页面
        const currentUrl = window.location.href.split('?')[0]
        const needArr = needTracks.filter(itemA => {
            const urls = itemA.rule.urls
            if (!urls) {
                return true
            } else {
                const urlArr = urls.filter(item => { return currentUrl === item })
                return (urls && !urls.length) || urlArr.length
            }
        })
        // 查看id属性
        const endArr = needArr.filter(item => item.rule.selectorId === clickBox.id)
        return endArr
    }
}